package hu.gbalage.owlforms.internal;

import java.io.File;
import java.lang.reflect.Constructor;
import java.net.*;
import java.util.LinkedList;

import org.semanticweb.owl.inference.OWLReasoner;
import org.semanticweb.owl.model.OWLOntologyManager;

public class ReasonerPlugin {

	private LinkedList<URL> urls = new LinkedList<URL>();
	private URLClassLoader classloader;
	
	private void addFile(File f){
		//System.out.print(".."+f+"..");
		if (f.isDirectory()){
			//System.out.println("Entering.");
			for(File d : f.listFiles()){
				addFile(d);
			}
		}else{
			try{
				urls.add(f.toURI().toURL());
				//System.out.println("Added.");
			}catch(MalformedURLException e){
				//do nothing
			}
		}
	}
	
	public ReasonerPlugin(File dir){
		addFile(dir);
		//URL[] urs = (URL[])(urls.toArray());
		//System.out.print("Creating classloader...");
		classloader = new URLClassLoader((URL[])(urls.toArray(new URL[0])), ClassLoader.getSystemClassLoader());
		//System.out.println("Done.");
	}
	
	public OWLReasoner getReasoner(String classname,OWLOntologyManager manager){
		try{
			Class<?> reasonerClass = classloader.loadClass(classname);
			//System.out.println("Reasoner found: "+reasonerClass);
			Constructor<?> con = reasonerClass.getConstructor(OWLOntologyManager.class);
			return (OWLReasoner)con.newInstance(manager);
		}catch(Exception e){
			System.err.println("Error loading Reasoner: "+e.getLocalizedMessage());
			return null;
		}
	}
}
